package org.jhub1.system.xmpp.commands;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.jhub1.system.xmpp.proxy.ProcessorSession;

public class NewMessageProcessor {

	Map<String, Executable> aMap;

	public NewMessageProcessor() {
		aMap = new HashMap<String, Executable>();
		ProcessorSession.getInstance();
	}

	public void registerElement(String name, Executable element) {
		if(!aMap.containsKey(name)) {
			aMap.put(name, element);
		}
	}

	public ReturnMessage process(RequestMessage rm) {
		ReturnMessage retme = null;
		if (ProcessorSession.isActive()) {
		if (rm.getCommand().equalsIgnoreCase("help")) {
			ProcessorSession.prolongSession();
			retme = new ReturnMessage(rm);
			retme.setMessage(getHelp());
		} else {
			if(aMap.containsKey(rm.getCommand())) {
				Executable ex = (Executable)aMap.get(rm.getCommand());
				retme = ex.executeCommand(rm);
			} else {
				retme = new ReturnMessage(rm);
				retme.setMessage("Command not found!");
				retme.setExtStatus(ReturnMessage.REFUSED);
			}
		}
		} else {
			if(rm.getCommand().equals("?StartSession")) {
				Executable ex = (Executable)aMap.get(rm.getCommand());
				retme = ex.executeCommand(rm);
			} else {
				retme = null;
			}
		}
		if(retme != null && retme.isStatus()) {
			ProcessorSession.prolongSession();
		}
		return retme;
	}

	public String getHelp() {
	    Iterator<Entry<String, Executable>> it = aMap.entrySet().iterator();
	    StringBuilder sb = new StringBuilder();
	    sb.append("\n");
	    while (it.hasNext()) {
	        Map.Entry<String, Executable> pairs = (Map.Entry<String, Executable>)it.next();
	        Element el = (Element) pairs.getValue();
	        if (el.getHelpLine() != null) {
	        	sb.append(el.getHelpLine());
	        }
	     //   it.remove();
	    }
	    sb.append("help - Displays this list");
		return sb.toString();
	}

	// special function login logout help

}
